﻿using Entitas;
using UnityEngine;

public class GameController : MonoBehaviour
{
    public string recordPath = "";
    public bool replayMode = false;
    public bool recordMode = false;
    public int randomSeed = 0;

    private Systems _gameSystems;

    private void Start()
    {
        Services services = replayMode ? CreateReplayServices() : CreateServices();
        Initialize();
        _gameSystems = CreateGameSystems(Contexts.sharedInstance, services);
        _gameSystems.Initialize();
    }

    private void Update()
    {
        _gameSystems.Execute();
        _gameSystems.Cleanup();
    }

    private void OnDestroy()
    {
        _gameSystems.TearDown();
        //Contexts.sharedInstance.Reset();
    }

    private Systems CreateGameSystems(Contexts contexts, Services services)
    {
        Systems logicSystems = CreateLogicSystems(contexts, services);

        TickSystem tickSystem = new TickSystem(services.Time, logicSystems);

        return new Systems()
            .Add(tickSystem);
    }

    private Systems CreateLogicSystems(Contexts contexts, Services services)
    {
        return new Feature("LogicSystems")
            .Add(new GraphSystem(services.View))
            .Add(new InputSystem(services.Input))
            .Add(new RecordSystem(services.ExportRecord))
            .Add(new CreateSystem(services.View))
            .Add(new PlayerControllerSystem())
            .Add(new CellSpaceSystem(services.View))
            .Add(new SteerBehaviorSystem())
            .Add(new MoveSystem())
            .Add(new SpawnSystem(services.View))
            .Add(new ArriveToDieSystem())
            .Add(new DestroySystem());
    }

    private Services CreateServices()
    {
        return new Services(
            new UnityViewService(),
            new UnityInputService(),
            new UnityTimeService(),
            new TxtExportRecordService());
    }

    private Services CreateReplayServices()
    {
        return new Services(
            new UnityViewService(),
            new RecordInputService(),
            new UnityTimeService(),
            null);
    }

    private void Initialize()
    {
        Contexts.sharedInstance.game.SetRecordGlobal(recordPath, replayMode, recordMode);
        Contexts.sharedInstance.game.SetRandom(new System.Random(randomSeed));
    }
}